package com.example.scenictourback.controller;

import com.example.scenictourback.common.Result;
import com.example.scenictourback.dto.LoginDTO;
import com.example.scenictourback.dto.RegisterDTO;
import com.example.scenictourback.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private AuthService authService;
    
    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<?> login(@RequestBody @Valid LoginDTO loginDTO) {
        Map<String, Object> result = authService.login(loginDTO);
        return Result.success("登录成功", result);
    }
    
    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<?> register(@RequestBody @Valid RegisterDTO registerDTO) {
        boolean success = authService.register(registerDTO);
        return success ? Result.success("注册成功") : Result.error("注册失败");
    }
    
    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<?> logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            authService.logout(token);
            return Result.success("退出成功");
        }
        return Result.error("退出失败");
    }
} 